//
//  MyController.m
//  CocoaDeg
//
//  Created by Stéphane Delval on 11/01/10
//  Copyright 2010 BiWiLabs. All rights reserved.
//

#import "MyController.h"
#import "SecondDegSolver.h"

@implementation MyController
- (IBAction)calculateAnswer:(id)sender
{
    // Let's instantiate "myProblemToSolve", representing the object of my class "SecondDegSolver":
    SecondDegSolver *myProblemToSolve = [[SecondDegSolver alloc]init];
    
    // Now I can use my new object:
    if ( [myProblemToSolve getSolution: [aInputValue doubleValue]
                                Term_B: [bInputValue doubleValue]
                                Term_C: [cInputValue doubleValue]] == MSG_SUCCESS )
    {
        // read the "number of digits after decimal" value from the preference file
        int digitsAfterDecimal = [[NSUserDefaults standardUserDefaults] integerForKey:@"nrOfDigitsAfterDecimal"];

        // display the two solutions
        [answerX1 setDoubleValue:[myProblemToSolve getFirstSolution: digitsAfterDecimal]];
        [answerX2 setDoubleValue:[myProblemToSolve getSecondSolution: digitsAfterDecimal]];
    }
    else
    {
        // display non-numeric characters to suggest an error (delta negative or other error)
        [answerX1 setStringValue:@"###"];
        [answerX2 setStringValue:@"###"];
        
        NSAlert * alert = [NSAlert alertWithMessageText: @"There is no real solution" 
                                          defaultButton: @"OK" 
                                        alternateButton: nil 
                                            otherButton: nil 
                              informativeTextWithFormat: @""]; 
        [alert runModal];
    }
    [myProblemToSolve release];
}

- (IBAction)showPreferences:(id)sender
{
    if(!preferenceController)
    {
        preferenceController = [[PreferenceController alloc] init];
    }
    //NSLog(@"Pref Window has been asked to show itself!"); // *** DEBUG ***
    [preferenceController showWindow:self];
}

- (void)dealloc
{
    [preferenceController release]; //Check why this method is never called!
    //NSLog(@"I've been killed!"); // *** DEBUG ***
    [super dealloc];
}

+(void)initialize
{
    // This method seems to be executed once, at startup.
    // I don't really know why and how, but it's just fine.

    // We'll use this method to initialize the app's parameters
    // if the app has never been launched.
    NSString *prefValue = [[NSUserDefaults standardUserDefaults] valueForKey:@"nrOfDigitsAfterDecimal"];

    // Check if the preferences already exist. If the preference
    // file does not exist, a new one is created with default values
    if (prefValue == nil)
    {
        //NSLog(@"A new preference file has been created");
        [[NSUserDefaults standardUserDefaults] setInteger:(int)5 forKey:@"nrOfDigitsAfterDecimal"];
    }
    else
    {
        //NSLog(@"The preference file already exists"); // *** DEBUG ***
        //do nothing
    }
}

@end
